import typescript from '@rollup/plugin-typescript';
import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import del from 'rollup-plugin-delete';
import dts from 'rollup-plugin-dts';

const mode = process.env.BUILD || 'development';
const isProd = mode === 'production';

export default [
    {
        input: 'src/index.ts',
        output: {
            file: 'dist/shimotsuki_core.js',
            format: 'esm',
            sourcemap: false, // 关闭 sourcemap 生成
        },
        context: 'globalThis',
        external: ['cc', 'cc/env'], // 根据项目实际情况调整
        plugins: [
            // resolve({
            //     preferBuiltins: false,
            //     extensions: ['.js', '.ts'],
            // }),
            // commonjs(),
            typescript({
                declaration: true,
                declarationDir: 'dist/temp', // 临时存放声明文件
                outDir: 'dist',
                rootDir: 'src',
            }),
            babel({
                babelHelpers: 'runtime',
                extensions: ['.js', '.ts'],
                exclude: /node_modules\/(?!@babel\/runtime-corejs3)/, // 只排除非 runtime-corejs3 的 node_modules
                presets: [
                    [
                        '@babel/preset-env',
                        {
                            targets: '> 0.25%, not dead',
                            useBuiltIns: false, // 关闭 preset-env 自动注入 polyfill，交给 transform-runtime 处理
                        },
                    ],
                ],
                plugins: [
                    [
                        '@babel/plugin-transform-runtime',
                        {
                            corejs: 3,
                            helpers: true,
                            regenerator: true,
                            useESModules: true,
                        },
                    ],
                ],
            }),
            isProd
                ? terser({
                      mangle: { keep_classnames: true },
                      keep_classnames: true,
                      format: { comments: false },
                  })
                : terser({
                      mangle: { keep_classnames: true },
                      keep_classnames: true,
                      compress: false,
                      format: { beautify: true },
                  }),
        ],
    },
    // DTS 构建配置
    {
        input: 'dist/temp/index.d.ts',
        output: {
            file: 'dist/index.d.ts',
            format: 'esm',
        },
        external: ['cc', 'cc/env'], // 添加 external 模块
        plugins: [
            dts(), // 构建完成后删除临时目录
            del({
                targets: 'dist/temp',
                hook: 'buildEnd',
            }),
        ],
    },
];
